package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.constant.ProductConstant;
import com.atguigu.gulimall.common.utils.Constant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        // 保存基本数据
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);

        // 如果为基础类型才需要设置关联表
        if (attrVo.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) &&
            attrVo.getAttrGroupId() != null){
            // 保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }

    }

    /**
     * 查询基础规格参数
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        LambdaQueryWrapper<AttrEntity> lambdaQueryWrapper = new LambdaQueryWrapper<AttrEntity>()
                .eq(StringUtils.isNotEmpty(attrType),AttrEntity::getAttrType,"base".equalsIgnoreCase(attrType)?1:0);

        if(catelogId != 0){
            lambdaQueryWrapper.eq(AttrEntity::getCatelogId,catelogId);
        }

        // 添加检索条件
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            lambdaQueryWrapper.and((obj) -> {
                obj.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                lambdaQueryWrapper
        );

        List<AttrEntity> records = page.getRecords();

        // 设置分类名和分组名
        List<AttrRespVo> respRecords = records.stream().map((item) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item,attrRespVo);

            // 1、设置分组名 （只有在被查询为基础属性时才设置）
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attrRespVo.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            // 2、设置分类名
            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
            if (categoryEntity != null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(respRecords);
        return pageUtils;

    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        // 先查当前属性的详细信息
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);

        // 1、查询并设置分组信息（限于基本属性）
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));
            if (relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogePath = categoryService.findCatelogePath(catelogId);
        attrRespVo.setCatelogPath(catelogePath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if (categoryEntity != null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attrVo) {
        // 基础修改
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.updateById(attrEntity);

        // 基础属性还要修改分组信息
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            Integer count = relationDao.selectCount(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrVo.getAttrId()));
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            if (count > 0) {
                // 关系表中有值，说明是进行修改
                // 修改分组关联
                relationDao.update(relationEntity, new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attrVo.getAttrId()));
            } else {
                // 反之就进行新增
                relationDao.insert(relationEntity);

            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId));
        List<Long> attrIds ;
        if(relationEntities != null) {
            attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            if (attrIds.size() > 0)
            return this.listByIds(attrIds);
        }
//        System.out.println(attrIds);
        return null;
    }

    /**
     * 删除属性与分组的关系
     * @param relationVos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] relationVos) {
//        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        List<Long> ids = Arrays.stream(relationVos).map((item) -> {
//            BeanUtils.copyProperties(item,relationEntity);
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AttrAttrgroupRelationEntity::getAttrId,item.getAttrId())
                    .eq(AttrAttrgroupRelationEntity::getAttrGroupId,item.getAttrGroupId());

            return relationDao.selectOne(lambdaQueryWrapper).getId();
        }).collect(Collectors.toList());
/*        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.stream(relationVos).map((item) -> {
            BeanUtils.copyProperties(item,relationEntity);
            return relationEntity; }).collect(Collectors.toList());
        System.out.println(relationEntities);

        relationDao.deleteBatchRelation(relationEntities);*/

        relationDao.deleteBatchIds(ids);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 1、当前分组只能关联到自己所属分类里的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2、当前分组只能关联别的分组没有引用的属性
        // 2、1）找到当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new LambdaUpdateWrapper<AttrGroupEntity>()
                .eq(catelogId != null, AttrGroupEntity::getCatelogId, catelogId));

        // 2、2）查询这些分组关联的所有属性
        List<Long>
            groupIds = attrGroupEntities == null? null : attrGroupEntities.stream()
                    .map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
            // 拿到其他关联的集合
            List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>()
                    .in(groupIds != null && groupIds.size() > 0, AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
            List<Long> attrList = relationEntities == null ? null : relationEntities.stream()
                    .map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            // 拿到当前分组可以关联的其他属性
        LambdaUpdateWrapper<AttrEntity> wrapper = new LambdaUpdateWrapper<AttrEntity>()
                .eq(catelogId != null, AttrEntity::getCatelogId, catelogId)
                .notIn(attrList != null && attrList.size() > 0, AttrEntity::getAttrId, attrList)
                .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        // 封装模糊查询条件
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((obj) -> {
                obj.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

}